package org.goldfish.distributed_framework.server;

import org.goldfish.distributed_framework.client.RpcRequest;
import org.goldfish.distributed_framework.client.RpcResponse;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

public class RpcWorker implements Runnable {
    private final Socket socket;

    public RpcWorker(Socket socket) {
        this.socket = socket;
    }


    @Override
    public void run() {
        try (
                ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
                ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream())
        ) {
            System.out.println("等待客户端发送请求...");
            Object request = in.readObject(); // 读入一个对象
            System.out.println("收到请求: " + request);

            if (request instanceof RpcRequest rpcRequest) {
                // 调用已注册的本地服务
                Object result = ServiceProvider.invoke(rpcRequest);
                // 返回给客户端
                out.writeObject(result);
                out.flush();
                System.out.println("响应已发送: " + result);
            } else {
                System.err.println("收到非法请求: " + request);
                RpcResponse error = RpcResponse.failure("Invalid request type: " + request.getClass());
                out.writeObject(error);
                out.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



}
